package com.smag.web.controller.system;

import com.smag.common.annotation.Log;
import com.smag.common.constant.UserConstants;
import com.smag.common.core.controller.BaseController;
import com.smag.common.core.domain.AjaxResult;
import com.smag.common.core.domain.entity.FarmCategory;
import com.smag.common.enums.BusinessType;
import com.smag.common.utils.StringUtils;
import com.smag.system.service.FarmCategoryService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import static com.smag.common.core.domain.AjaxResult.error;
import static com.smag.common.core.domain.AjaxResult.success;


@RestController
@RequestMapping("/system/category")
public class SysCategoryController extends BaseController{
    @Resource
    private FarmCategoryService farmCategoryService;

    @GetMapping
    @PreAuthorize("@ss.hasPermi('system:category:query')")
    public AjaxResult listCategory(){
        return farmCategoryService.selectAllCategory();
    }

    @GetMapping("/children")
    @PreAuthorize("@ss.hasPermi('system:category:query')")
    public AjaxResult listCategoryChildren(){
        return farmCategoryService.selectAllCategoryChildren();
    }


    /**
     * 查询种类列表
     */
    @PreAuthorize("@ss.hasPermi('system:category:list')")
    @GetMapping("/list")
    public AjaxResult list(FarmCategory farmCategory)
    {
        List<FarmCategory> list = farmCategoryService.selectFarmCategoryList(farmCategory);
        return success(list);
    }

    /**
     * 获取种类详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:category:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        farmCategoryService.checkCategoryDataScope(id);
        return success(farmCategoryService.selectFarmCategoryById(id));
    }

    /**
     * 查询种类列表（排除节点）
     */
    @GetMapping("/list/exclude/{id}")
    public AjaxResult excludeChild(@PathVariable(value = "id", required = false) Long id)
    {
        List<FarmCategory> farmCategories = farmCategoryService.selectFarmCategoryList(new FarmCategory());
        farmCategories.removeIf(d -> d.getId().intValue() == id || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), id + ""));
        return success(farmCategories);
    }

    /**
     * 新增种类
     */
    @PreAuthorize("@ss.hasPermi('system:category:add')")
    @Log(title = "种类", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FarmCategory farmCategory)
    {
        if(!farmCategoryService.checkCategoryNameUnique(farmCategory)){
            return error("新增分类'"+farmCategory.getName()+"'失败，分类名称已存在");
        }
        return toAjax(farmCategoryService.insertFarmCategory(farmCategory));
    }

    /**
     * 修改种类
     */
    @PreAuthorize("@ss.hasPermi('system:category:edit')")
    @Log(title = "种类", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FarmCategory farmCategory)
    {
        Long categoryId =farmCategory.getId();
        farmCategoryService.checkCategoryDataScope(categoryId);
        if (!farmCategoryService.checkCategoryNameUnique(farmCategory))
        {
            return error("修改分类'" + farmCategory.getName() + "'失败，分类名称已存在");
        }
        else if (farmCategory.getPid().equals(categoryId))
        {
            return error("修改分类'" + farmCategory.getName() + "'失败，上级分类不能是自己");
        }
        else if (StringUtils.equals(UserConstants.CATE_DISABLE,farmCategory.getStatus())&&farmCategoryService.selectNormalChildrenCategoryById(categoryId)>0)
        {
            return error("该分类包含未停用的子分类！");
        }
        return toAjax(farmCategoryService.updateFarmCategory(farmCategory));
    }

    /**
     * 删除种类
     */
    @PreAuthorize("@ss.hasPermi('system:category:remove')")
    @Log(title = "种类", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id)
    {
        if(farmCategoryService.hasChildCategoryById(id))
        {
            return warn("存在下级种类，不允许删除");
        }
        if (farmCategoryService.checkCategoryExistCrop(id)){
            return warn("种类存在作物信息，不允许删除");
        }
        farmCategoryService.checkCategoryDataScope(id);//未测试
        return toAjax(farmCategoryService.deleteFarmCategoryById(id));
    }


  /* 农作物页面需要构建tree
   @GetMapping("/categoryTree")
    public AjaxResult categoryTree(FarmCategory farmCategory)
    {
        return success(farmCategoryService.selectCategoryTreeList(farmCategory));
    }*/
}
